import { defineStore } from 'pinia'
import { ref } from 'vue'
//引入接口
import { getHrIsHrById } from '@/servers/controller'
import {
  postAuthLoginEmail,
  postAuthLoginPwd,
  postAuthRegister,
} from '../../servers/controller/1.RenZhengMoKuai'
import type {
  LoginDto,
  EmailAndCaptchaDto,
  UserInfoVo,
  RegisterDto,
} from '../../servers/interface/index'
import { getUserOne } from '../../servers/controller/3.YongHuMoKuai'
//引入操作本地存储的工具方法
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { ElMessage } from 'element-plus'
import pinia from '..'
import router from '@/router'
import { useRoute } from 'vue-router'
import { JobType } from '@/api/job/type'
import { asyncRoute } from '@/router/routes'

//创建用户小仓库
const useUserStore = defineStore('User', () => {
  const route = useRoute()
  const token = ref<string>(GET_TOKEN() as string)
  const sideMode = ref<string>('#fff')
  const activeColor = ref<string>('#1890ff')
  const isHr = ref(0)
  const userInfo = ref<UserInfoVo>({
    id: 0,
    username: '',
    name: '',
    avatar: '',
    email: '',
    phone: '',
    createTime: '',
  })
  const needToChatJobInfo = ref<JobType>()

  async function userLogin(params: LoginDto) {
    try {
      const { data } = await postAuthLoginPwd(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      await judgeHr()
      //编程式导航跳转到展示数据首页
      //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
      if (isHr.value === 1) {
        // let redirect: any = route.query.redirect
        // console.log("is hr")
        // router.replace({ path: redirect || 'hr' })
        asyncRoute.forEach((item) => router.addRoute(item))
        router.push('/hr/home')
      } else {
        // let redirect: any = route.query.redirect
        // console.log("is not hr")
        // router.replace({ path: redirect || 'home' })
        router.push('/')
      }
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function userRegister(params: RegisterDto) {
    try {
      const { data } = await postAuthRegister(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      // await getUserInfo()
      //编程式导航跳转到展示数据首页
      //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
      // let redirect: any = route.query.redirect
      // router.replace({ path: redirect || 'home' })
    } catch (error) {
      //登录失败的提示信息
      ElMessage({
        type: 'error',
        message: (error as Error).message,
      })
    }
  }

  async function userLoginByEmail(params: EmailAndCaptchaDto) {
    try {
      const { data } = await postAuthLoginEmail(params)
      //pinia仓库存储一下token
      //由于pinia|vuex存储数据其实利用js对象
      token.value = data.data.token
      //本地存储持久化存储一份
      SET_TOKEN(token.value)
      await getUserInfo()
      await judgeHr()
      //编程式导航跳转到展示数据首页
      //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
      if (isHr.value === 1) {
        // let redirect: any = route.query.redirect
        // console.log("is hr")
        // router.replace({ path: redirect || 'hr' })
        asyncRoute.forEach((item) => router.addRoute(item))
        router.push('/hr/home')
      } else {
        // let redirect: any = route.query.redirect
        // console.log("is not hr")
        // router.replace({ path: redirect || 'home' })
        router.push('/')
      }
    } catch (error) {
      //登录失败的提示信息
      Promise.reject((error as Error).message)
    }
  }

  async function getUserInfo() {
    try {
      const { data } = await getUserOne()
      userInfo.value = data.data
    } catch (error) {
      if (error instanceof Error) {
        ElMessage.error(error.message)
        Promise.reject(new Error(error.message))
      }
    }
  }

  async function judgeHr() {
    try {
      //@ts-ignore
      const res = await getHrIsHrById({ id: userInfo.value.id })
      isHr.value = res.data.data
    } catch (error) {
      if (error instanceof Error) {
        ElMessage.error(error.message)
        Promise.reject(new Error(error.message))
      }
    }
  }

  async function userLogout() {
    REMOVE_TOKEN()
    token.value = ''
    userInfo.value = {
      id: 0,
      username: '',
      name: '',
      avatar: '',
      email: '',
      phone: '',
      createTime: '',
    }
  }

  return {
    token,
    userInfo,
    isHr,
    sideMode,
    activeColor,
    needToChatJobInfo,
    userLogout,
    userRegister,
    userLogin,
    userLoginByEmail,
    getUserInfo,
    judgeHr,
  }
})
//对外暴露获取小仓库方法
export default useUserStore

// 非setup
export function useUserStoreHook() {
  return useUserStore(pinia)
}
